package com.example.handheld4_gsignal_app.services;

import android.content.Context;
import com.example.handheld4_gsignal_app.data.SignalRecord;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据分析服务 - 提供信号数据的统计分析功能
 */
public class DataAnalysisService {
    
    private Context context;
    private DecimalFormat decimalFormat;
    
    public DataAnalysisService(Context context) {
        this.context = context;
        this.decimalFormat = new DecimalFormat("#.##");
    }
    
    /**
     * 分析信号数据
     */
    public String analyzeSignalData(List<SignalRecord> records) {
        if (records == null || records.isEmpty()) {
            return "没有数据可分析";
        }
        
        StringBuilder analysis = new StringBuilder();
        
        // 基本统计信息
        analysis.append("📊 基本统计信息\n");
        analysis.append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
        analysis.append("总记录数: ").append(records.size()).append(" 条\n");
        analysis.append("数据时间范围: ").append(getTimeRange(records)).append("\n");
        analysis.append("覆盖区域: ").append(getCoverageArea(records)).append("\n\n");
        
        // 信号强度分析
        analysis.append("📶 信号强度分析\n");
        analysis.append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
        analysis.append(getSignalStrengthAnalysis(records)).append("\n");
        
        // 网络类型分析
        analysis.append("📡 网络类型分析\n");
        analysis.append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
        analysis.append(getNetworkTypeAnalysis(records)).append("\n");
        
        // 运营商分析
        analysis.append("🏢 运营商分析\n");
        analysis.append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
        analysis.append(getOperatorAnalysis(records)).append("\n");
        
        // 位置分析
        analysis.append("📍 位置分析\n");
        analysis.append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
        analysis.append(getLocationAnalysis(records)).append("\n");
        
        // 质量评估
        analysis.append("⭐ 信号质量评估\n");
        analysis.append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
        analysis.append(getQualityAssessment(records)).append("\n");
        
        return analysis.toString();
    }
    
    /**
     * 获取时间范围
     */
    private String getTimeRange(List<SignalRecord> records) {
        if (records.isEmpty()) return "无数据";
        
        String firstTime = records.get(0).getCollectedAt();
        String lastTime = records.get(records.size() - 1).getCollectedAt();
        return firstTime + " 至 " + lastTime;
    }
    
    /**
     * 获取覆盖区域
     */
    private String getCoverageArea(List<SignalRecord> records) {
        if (records.isEmpty()) return "无数据";
        
        double minLat = records.stream().mapToDouble(SignalRecord::getLatitude).min().orElse(0);
        double maxLat = records.stream().mapToDouble(SignalRecord::getLatitude).max().orElse(0);
        double minLng = records.stream().mapToDouble(SignalRecord::getLongitude).min().orElse(0);
        double maxLng = records.stream().mapToDouble(SignalRecord::getLongitude).max().orElse(0);
        
        return String.format("纬度: %.4f ~ %.4f, 经度: %.4f ~ %.4f", 
            minLat, maxLat, minLng, maxLng);
    }
    
    /**
     * 信号强度分析
     */
    private String getSignalStrengthAnalysis(List<SignalRecord> records) {
        List<Integer> strengths = records.stream()
            .mapToInt(SignalRecord::getSignalStrength)
            .boxed()
            .collect(Collectors.toList());
        
        double avg = strengths.stream().mapToInt(Integer::intValue).average().orElse(0);
        int min = Collections.min(strengths);
        int max = Collections.max(strengths);
        
        // 信号质量分级
        long excellent = strengths.stream().filter(s -> s >= -70).count();
        long good = strengths.stream().filter(s -> s >= -85 && s < -70).count();
        long fair = strengths.stream().filter(s -> s >= -100 && s < -85).count();
        long poor = strengths.stream().filter(s -> s < -100).count();
        
        StringBuilder result = new StringBuilder();
        result.append("平均信号强度: ").append(decimalFormat.format(avg)).append(" dBm\n");
        result.append("最强信号: ").append(max).append(" dBm\n");
        result.append("最弱信号: ").append(min).append(" dBm\n");
        result.append("信号范围: ").append(max - min).append(" dBm\n\n");
        
        result.append("信号质量分布:\n");
        result.append("优秀 (≥-70dBm): ").append(excellent).append(" 条 (").append(getPercentage(excellent, records.size())).append("%)\n");
        result.append("良好 (-85~-70dBm): ").append(good).append(" 条 (").append(getPercentage(good, records.size())).append("%)\n");
        result.append("一般 (-100~-85dBm): ").append(fair).append(" 条 (").append(getPercentage(fair, records.size())).append("%)\n");
        result.append("较差 (<-100dBm): ").append(poor).append(" 条 (").append(getPercentage(poor, records.size())).append("%)\n");
        
        return result.toString();
    }
    
    /**
     * 网络类型分析
     */
    private String getNetworkTypeAnalysis(List<SignalRecord> records) {
        Map<String, Long> networkTypes = records.stream()
            .collect(Collectors.groupingBy(
                record -> record.getNetworkType() != null ? record.getNetworkType() : "未知",
                Collectors.counting()
            ));
        
        StringBuilder result = new StringBuilder();
        for (Map.Entry<String, Long> entry : networkTypes.entrySet()) {
            String type = entry.getKey();
            long count = entry.getValue();
            result.append(type).append(": ").append(count).append(" 条 (")
                  .append(getPercentage(count, records.size())).append("%)\n");
        }
        
        return result.toString();
    }
    
    /**
     * 运营商分析
     */
    private String getOperatorAnalysis(List<SignalRecord> records) {
        Map<String, Long> operators = records.stream()
            .collect(Collectors.groupingBy(
                record -> {
                    String operatorName = record.getOperatorName();
                    if (operatorName == null || operatorName.isEmpty()) {
                        return "未知";
                    }
                    // 修复字符编码问题
//                    try {
//                        // 重新编码确保中文字符正确显示
//                        byte[] bytes = operatorName.getBytes("ISO-8859-1");
//                        return new String(bytes, "UTF-8");
//                    } catch (Exception e) {
//                        // 如果编码转换失败，返回原始字符串
//                        return operatorName;
//                    }
                    return operatorName;
                },
                Collectors.counting()
            ));
        
        StringBuilder result = new StringBuilder();
        for (Map.Entry<String, Long> entry : operators.entrySet()) {
            String operator = entry.getKey();
            long count = entry.getValue();
            result.append(operator).append(": ").append(count).append(" 条 (")
                  .append(getPercentage(count, records.size())).append("%)\n");
        }
        
        return result.toString();
    }
    
    /**
     * 位置分析
     */
    private String getLocationAnalysis(List<SignalRecord> records) {
        // 计算中心点
        double centerLat = records.stream().mapToDouble(SignalRecord::getLatitude).average().orElse(0);
        double centerLng = records.stream().mapToDouble(SignalRecord::getLongitude).average().orElse(0);
        
        // 计算覆盖半径（简化计算）
        double maxDistance = 0;
        for (SignalRecord record : records) {
            double distance = calculateDistance(centerLat, centerLng, 
                record.getLatitude(), record.getLongitude());
            maxDistance = Math.max(maxDistance, distance);
        }
        
        StringBuilder result = new StringBuilder();
        result.append("中心位置: ").append(decimalFormat.format(centerLat))
              .append(", ").append(decimalFormat.format(centerLng)).append("\n");
        result.append("覆盖半径: ").append(decimalFormat.format(maxDistance)).append(" 公里\n");
        result.append("数据点分布: ").append(records.size()).append(" 个位置点\n");
        
        return result.toString();
    }
    
    /**
     * 质量评估
     */
    private String getQualityAssessment(List<SignalRecord> records) {
        double avgSignal = records.stream().mapToInt(SignalRecord::getSignalStrength).average().orElse(0);
        long goodSignals = records.stream().filter(s -> s.getSignalStrength() >= -85).count();
        double goodSignalRatio = (double) goodSignals / records.size();
        
        StringBuilder result = new StringBuilder();
        
        // 整体评分
        int score = calculateQualityScore(avgSignal, goodSignalRatio);
        result.append("整体信号质量评分: ").append(score).append("/100\n");
        
        // 质量等级
        String qualityLevel = getQualityLevel(score);
        result.append("质量等级: ").append(qualityLevel).append("\n");
        
        // 建议
        result.append("建议:\n");
        if (score >= 80) {
            result.append("✅ 信号质量优秀，网络连接稳定\n");
        } else if (score >= 60) {
            result.append("⚠️ 信号质量良好，偶有波动\n");
        } else if (score >= 40) {
            result.append("⚠️ 信号质量一般，建议检查网络环境\n");
        } else {
            result.append("❌ 信号质量较差，建议更换位置或联系运营商\n");
        }
        
        return result.toString();
    }
    
    /**
     * 计算质量评分
     */
    private int calculateQualityScore(double avgSignal, double goodSignalRatio) {
        // 信号强度评分 (0-60分)
        int signalScore = Math.max(0, Math.min(60, (int)((avgSignal + 120) * 0.6)));
        
        // 稳定性评分 (0-40分)
        int stabilityScore = (int)(goodSignalRatio * 40);
        
        return signalScore + stabilityScore;
    }
    
    /**
     * 获取质量等级
     */
    private String getQualityLevel(int score) {
        if (score >= 80) return "优秀 ⭐⭐⭐⭐⭐";
        if (score >= 60) return "良好 ⭐⭐⭐⭐";
        if (score >= 40) return "一般 ⭐⭐⭐";
        if (score >= 20) return "较差 ⭐⭐";
        return "很差 ⭐";
    }
    
    /**
     * 计算两点间距离（公里）
     */
    private double calculateDistance(double lat1, double lng1, double lat2, double lng2) {
        final int R = 6371; // 地球半径（公里）
        
        double latDistance = Math.toRadians(lat2 - lat1);
        double lngDistance = Math.toRadians(lng2 - lng1);
        
        double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
                + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
                * Math.sin(lngDistance / 2) * Math.sin(lngDistance / 2);
        
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        
        return R * c;
    }
    
    /**
     * 计算百分比
     */
    private String getPercentage(long count, int total) {
        if (total == 0) return "0";
        return decimalFormat.format((double) count / total * 100);
    }
}